#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
 @Author: Monox
 @Email: 627201584@qq.com
 @FileName: API_foundation.py
 @DateTime: 2023/2/22 21:06
 @SoftWare: PyCharm
"""
import requests
from requests.adapters import HTTPAdapter
import json
import hashlib
import urllib.parse

def GYYexecute(dic_data, GYsecret, GYurl):
    """
    GYY接口处理步骤
    1、构造签名前的请求参数 = dic_data
    2、dic_data转为无空格的json格式 = json_data
    3、json_data前后加上管易的secret = str_data
    4、通过str_data进行MD5加密得到 = sign
    5、将sign加入步骤1的dic_data里 = dic_data_new
    6、再将dic_data_new改为Json格式（无空格） = json_data_new
    7、将json_data_new调用API接口，得到python格式的响应报文 = pyresponse
    8、返回pyresponse
    9、判断返回数据是成功或者失败；成功返回详情(json格式)，失败返回sub_error_desc
    """
    json_data = NoJson(dic_data)
    str_data = GYsecret + json_data + GYsecret
    sign = genearteMD5(str_data)
    dic_data.setdefault("sign", sign)
    json_data_new = NoJson(dic_data)
    pyresponse = RequestsApi(json_data_new, GYurl)
    print(judgment_success(pyresponse))
    return pyresponse

def NoJson(data):
    """
    003
    转为没有空格的json格式
    """
    jsonData = json.dumps(data, separators=(',', ':'), ensure_ascii=False)  # 转为json,没有空格
    return jsonData

def genearteMD5(str):
    """
    003
    生成MD5（MD5加密）返回sign
    """
    # 创建md5对象
    hl = hashlib.md5()

    # Tips
    # 此处必须声明encode
    # 否则报错为：hl.update(str)    Unicode-objects must be encoded before hashing
    hl.update(str.encode(encoding='utf-8'))

    # print('MD5加密前为 ：' + str)
    # print('MD5加密后为 ：' + hl.hexdigest())
    return hl.hexdigest()  # 返回sign

def RequestsApi(data, GYurl):
    """
    003
    请求Requests
    """
    print(f'函数RequestsApi：请求报文：{data}')
    payload = urllib.parse.quote(str(data))  # URL编码 转义特殊字符
    url = GYurl
    headers = {
        'Content-Type': 'application/json'
    }
    s = requests.Session()
    s.mount('http://', HTTPAdapter(max_retries=3))  # 设置重试次数为3次
    s.mount('https://', HTTPAdapter(max_retries=3))
    try:
        response = requests.request("POST", url, headers=headers, data=payload, timeout=15)
        print(f'函数RequestsApi：返回报文：{response.text}')
        pyresponse = json.loads(response.text)  # json转python
        # print(pyresponse)  # 不用显示出来
        return pyresponse
    except Exception as e:
        print(f'请求Requests出现错误：{e}')
        pyresponse = {'success': False, 'errorCode': '', 'subErrorCode': '', 'errorDesc': '', 'subErrorDesc': '', 'delivery': None, 'code': None}
        return pyresponse

def item_detail_Merge(item_detail):
    """
    003
    item_detail商品明细根据[商品代码+批号+生产日期+到期日期+入库日期]进行排重处理
    """
    # print(f'原始item_detail：{item_detail}')
    itemQTY_dic = itemQTY_Merge_02(item_detail)
    # print(f"itemQTY_dic ： {itemQTY_dic}")
    # itemQTY_dic ： {'P.TS0041': 2, 'Z.WL002': 1, 'P.TS0043': 13}
    info_dic = {}
    for d in item_detail:  # 遍历原始item_detail，d为字典
        d2 = f"{d.get('item_code')},{d.get('batch_code')},{d.get('production_time')},{d.get('valid_time')},{d.get('warehousing_time')}"  # 这个作为判断唯一的id
        if d2 not in info_dic:  # 如果d2不在info_dic字典内
            # info_dic[d2] = str(d['qty']) +',' + str(d['price']) +',' + str(d['amount']) +',' + str(d['amountAfter'])
            info_dic[d2] = f"{d.get('qty')},{d.get('price')},{d.get('amount')},{d.get('amountAfter')}"
            # print(f"不在，info_dic[d['item_code']]:{info_dic[d['item_code']]}")
        else:  # 如果d2在info_dic字典内
            list1 = info_dic.get(d2).split(",")
            # info_dic[d2] = str(int(list1[0]) + d['qty']) +',' + str(float(list1[1]) + d['price']) +',' + str(float(list1[2]) + d['amount']) +',' + str(float(list1[3]) + d['amountAfter'])
            info_dic[
                d2] = f"{str(int(list1[0]) + d.get('qty'))},{str(float(list1[1]) + d.get('price'))},{str(float(list1[2]) + d.get('amount'))},{str(float(list1[3]) + d.get('amountAfter'))}"
            # print(f"else，info_dic[d['item_code']]:{info_dic[d['item_code']]}")
    # print(f"info_dic:{info_dic}")
    # info_dic:{'P.TS0044': '5,0.0,0.0,0.0', 'P.TS0043': '13,399.0,3990.0,3990.0'}
    new_info = []
    for n, v in info_dic.items():
        list_n = n.split(",")
        list_v = v.split(",")
        new_info.append({'item_code': list_n[0],
                         'batch_code': list_n[1],
                         'production_time': list_n[2],
                         'valid_time': list_n[3],
                         'warehousing_time': list_n[4],
                         'qty': int(list_v[0]),  # 数量
                         'price': float(float(list_v[2]) / int(itemQTY_dic.get(list_n[0]))),  # 单价
                         'amount': float(list_v[2]),  # 实际金额
                         'amountAfter': float(list_v[3])})  # 让利后金额
    # print(f"new_info:{new_info}")
    # new_info:[{'item_code': 'P.TS0044', 'qty': 5, 'price': 0.0, 'amount': 0.0, 'amountAfter': 0.0}, {'item_code': 'P.TS0043', 'qty': 13, 'price': 306.9230769230769, 'amount': 3990.0, 'amountAfter': 3990.0}]
    return new_info

def itemQTY_Merge_02(item_detail):
    """
    003
    item_detail商品明细根据[商品代码]进行排重处理,并返回对应商品代码的数量
    """
    # print(f'原始item_detail：{item_detail}')
    info_dic = {}
    for d in item_detail:  # 遍历原始item_detail，d为字典
        d2 = d.get('item_code')  # 这个作为判断唯一的id
        if d2 not in info_dic:  # 如果d2不在info_dic字典内
            # info_dic[d2] = str(d['qty']) +',' + str(d['price']) +',' + str(d['amount']) +',' + str(d['amountAfter'])
            info_dic[d2] = d.get('qty')
            # print(f"不在，info_dic[d['item_code']]:{info_dic[d['item_code']]}")
        else:  # 如果d2在info_dic字典内

            # info_dic[d2] = str(int(list1[0]) + d['qty']) +',' + str(float(list1[1]) + d['price']) +',' + str(float(list1[2]) + d['amount']) +',' + str(float(list1[3]) + d['amountAfter'])
            info_dic[d2] = f"{int(info_dic.get(d2)) + d.get('qty')}"
            # print(f"else，info_dic[d['item_code']]:{info_dic[d['item_code']]}")
    # print(f"info_dic:{info_dic}")
    # info_dic:{'P.TS0044': '5,0.0,0.0,0.0', 'P.TS0043': '13,399.0,3990.0,3990.0'}
    return info_dic

def judgment_success(pyresponse):
    """
    003
    判断是否同步成功并返回日志
    """
    success_data = pyresponse.get("success")
    if success_data == True:
        try:
            SDO_delivery = pyresponse.get("delivery")
            if SDO_delivery != None:
                SDO_delivery = SDO_delivery.get('code')
            RGO_code = pyresponse.get("code")
            Method = pyresponse.get("requestMethod")
            logdata = f'函数judgment_success：调用接口{Method}成功，发货单号为{SDO_delivery},退货单号为{RGO_code}'
        except Exception as e:
            logdata = f'函数judgment_success：处理报错：{e}'
        finally:
            return logdata
    elif success_data == False:
        try:
            Method = pyresponse.get("requestMethod")
            errorDesc = pyresponse.get("errorDesc")
            subErrorDesc = pyresponse.get("subErrorDesc")
            logdata = f'函数judgment_success：调用接口{Method}失败，errorDesc:{errorDesc}，subErrorDesc:{subErrorDesc}'
        except Exception as e:
            logdata = f'函数judgment_success：处理报错：{e}'
        finally:
            return logdata
    else:
        logdata = '函数judgment_success：处理失败'
        return logdata

if __name__ == '__main__':
    pass
